package com.sunyard.domee.common.config;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @program domee
 * @description 所有入参和返回将打印出来
 * @author raoinyx@163.com
 * @create 2020-07-18 00:23
 */
@Slf4j
@Configuration
@Aspect
public class RequestAspectConfig {


    @Pointcut("execution(* com.sunyard.domee.commons.controller.*.*(..))")
    public void log() {
    }

    @Before("log()")
    public void exBefore(JoinPoint joinPoint) {
        ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (sra == null) {
            return;
        }
        HttpServletRequest request = sra.getRequest();
        log.info("================SERVICE-START==============================");
        log.info("url:" + request.getRequestURL());
        log.info("method:" + request.getMethod());
        log.info("class method:" + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        List<Object> argList = new ArrayList<>();
        for (Object obj : joinPoint.getArgs()) {
            if (obj instanceof ServletRequest || obj instanceof ServletResponse || obj instanceof MultipartFile) {
                continue;
            }
            argList.add(obj);
        }
    }

    @After("log()")
    public void exAfter(JoinPoint joinPoint) {
        log.info("class method:" + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName()
                + "方法执行完毕！");
    }

    @AfterReturning(returning = "result", pointcut = "log()")
    public void exAfterReturning(Object result) {

        log.info("================SERVICE-END==============================");
    }

}
